﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace firewallCmd
{
    class Program
    {
        static void Main(string[] args)
        {

            string webServiceCmd = "netsh advfirewall firewall add rule name=\"NiRen Web Service\" dir=in action=allow protocol=TCP localport=1883";
            string resultStr = ExecuteInCmd(webServiceCmd);
            //Console.WriteLine("执行结果:" + resultStr);

            string mqttServiceCmd = "netsh advfirewall firewall add rule name=\"MQTT Service\" dir=in action=allow protocol=TCP localport=8088";
            resultStr = ExecuteInCmd(mqttServiceCmd);
            //Console.WriteLine("执行结果:" + resultStr);

            string redisServiceCmd = "netsh advfirewall firewall add rule name=\"Redis Service\" dir=in action=allow protocol=TCP localport=63793";
            resultStr = ExecuteInCmd(redisServiceCmd);
            //Console.WriteLine("执行结果:" + resultStr);

            string ntpServiceCmd = "netsh advfirewall firewall add rule name=\"NTP\" protocol=UDP dir=in localport=123 action=allow";
            resultStr = ExecuteInCmd(ntpServiceCmd);
            //Console.WriteLine("执行结果:" + resultStr);
        }

        /// <summary>
        /// 执行内部命令（cmd.exe 中的命令）
        /// </summary>
        /// <param name="cmdline">命令行</param>
        /// <returns>执行结果</returns>
        public static string ExecuteInCmd(string cmdline)
        {
            using (var process = new Process())
            {
                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.CreateNoWindow = true;
                process.Start();
                process.StandardInput.AutoFlush = true;
                process.StandardInput.WriteLine(cmdline + "&exit");

                //获取cmd窗口的输出信息  
                string output = process.StandardOutput.ReadToEnd();

                process.WaitForExit();
                process.Close();
                return output;
            }
        }
    }
}
